#coding=utf-8
'''
Created on 2016年3月4日
初始化
'''
import codecs
import sys
import time
import logging
import torndb


def init():

    # 避免 utf-8mb4的错误
    # from tornado.options import options
    codecs.register(lambda name: codecs.lookup('utf8') if name == 'utf8mb4' else None)
#     #设置sys的默认编码是utf-8
#     reload(sys)
#     sys.setdefaultencoding('utf-8')  # @UndefinedVariable
    
    
    # 解决torndb的mysql server has gone away的问题
    def _ensure_connected(self):
        # Mysql by default closes client connections that are idle for
        # 8 hours, but the client library does not report this fact until
        # you try to perform a query and it fails.  Protect against this
        # case by preemptively closing and reopening the connection
        # if it has been idle for too long (7 hours by default).
        if (self._db is None or
            (time.time() - self._last_use_time > self.max_idle_time)):
            self.reconnect()
        self._last_use_time = time.time()
        try:
            self._db.ping()
        except Exception as e:
            logging.exception(e)
            self.reconnect()
        
    torndb.Connection._ensure_connected = _ensure_connected